package com.example.android.codelabs.navigation
import Service.LoginService
import Untils.KeyboardUtils
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.MotionEvent
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity


class LoginActivtiy :AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        val titleTextView = findViewById<TextView>(R.id.textViewTitle)
        val usernameEditText = findViewById<EditText>(R.id.editTextUsername)
        val passwordEditText = findViewById<EditText>(R.id.editTextPassword)
        val loginButton = findViewById<Button>(R.id.buttonLogin)
        val buttonlogin = findViewById<Button>(R.id.buttonLogin)
        buttonlogin.setBackgroundColor(Color.BLACK);
        val buttonregister = findViewById<Button>(R.id.zhuche)
        buttonregister.setBackgroundColor(Color.RED);

        loginButton.setOnClickListener {
            val username = usernameEditText.text.toString()
            val password = passwordEditText.text.toString()
            val loginService = LoginService(this)
            val loginResult = loginService.login(username, password)
            if (username.isNotEmpty() && password.isNotEmpty()) {
                if (loginResult)
                {
                    val intent = Intent(this, MainActivity::class.java)
                    startActivity(intent)
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
                    usernameEditText.text.clear()
                    passwordEditText.text.clear()
                }
                // 这里只是简单打印，实际应用中可替换为网络请求等验证操作
                else {
                    Toast.makeText(this, "Please write the current username and password", Toast.LENGTH_SHORT).show()
                    usernameEditText.text.clear()
                    passwordEditText.text.clear()
                }
            }
        }
        val zhucebutton = findViewById<Button>(R.id.zhuche)
        zhucebutton.setOnClickListener{
            val intentzhuce = Intent(this, RegisterActivity::class.java)
            startActivity(intentzhuce)
        }


    }


    @Override
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev != null) {
            when (ev.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 获取当前获得焦点的View
                    val view = currentFocus
                    // 调用方法判断是否需要隐藏键盘
                    KeyboardUtils.hideKeyboard(ev, view, this)
                }
            }
        }
        return super.dispatchTouchEvent(ev)

    }

}